package jlxy.ise.eroad.activity;

import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.github.clans.fab.FloatingActionButton;
import com.github.clans.fab.FloatingActionMenu;
import com.google.gson.Gson;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.mikepenz.fontawesome_typeface_library.FontAwesome;
import com.mikepenz.iconics.IconicsDrawable;

import org.json.JSONObject;

import cz.msebera.android.httpclient.Header;
import jlxy.ise.eroad.R;
import jlxy.ise.eroad.base.BaseCompatActivity;
import jlxy.ise.eroad.bean.BiddingInfo;
import jlxy.ise.eroad.bean.NlServerRps;
import jlxy.ise.eroad.bean.PackageInfo;
import jlxy.ise.eroad.bean.ServerRpsInfo;
import jlxy.ise.eroad.util.SingleToast;
import jlxy.ise.eroad.util.WebUtil;


/**
 * @author chen
 */
public class OrderDetailActivity extends BaseCompatActivity {

    private static final String TAG = OrderDetailActivity.class.getSimpleName();

    private Toolbar toolbar;
    private TextView mTxInfo;
    private FloatingActionMenu mFabMenu;
    public static PackageInfo.DataBean sPackageInfo;
    public static int sType = 0;//0:没有菜单 1:有菜单

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_pkg_detail);
        initViews();
    }

    private void initViews() {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setTitle(R.string.order_detail);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                OrderDetailActivity.this.onBackPressed();
            }
        });

        mTxInfo = (TextView) findViewById(R.id.tx_pkg_detail);
        mFabMenu = (FloatingActionMenu) findViewById(R.id.fab_menu);
        initFloatBtn();
        initInfoShow();

    }
    private void initInfoShow(){
        StringBuilder sb = new StringBuilder();

        sb.append("收件人名称:\n");
        sb.append(sPackageInfo.getCname());
        sb.append("\n\n");

        sb.append("收件人电话:\n");
        sb.append(sPackageInfo.getCtel());
        sb.append("\n\n");

        sb.append("价格:\n");
        sb.append(sPackageInfo.getPrice());
        sb.append("\n\n");

        sb.append("运输内容:\n");
        sb.append(sPackageInfo.getInfo());
        sb.append("\n\n");

        sb.append("发货时间:\n");
        sb.append(sPackageInfo.getStime());
        sb.append("\n\n");

        sb.append("收货时间:\n");
        sb.append(sPackageInfo.getEtime());
        sb.append("\n\n");

        sb.append("发货地址:\n");
        sb.append(sPackageInfo.getSprovince()+sPackageInfo.getScity()+sPackageInfo.getSdistrict()+sPackageInfo.getSaddr());
        sb.append("\n\n");

        sb.append("收货地址:\n");
        sb.append(sPackageInfo.getEprovince()+sPackageInfo.getEcity()+sPackageInfo.getEdistrict()+sPackageInfo.getEaddr());
        sb.append("\n\n");

        mTxInfo.setText(sb.toString());
    }


    private void initFloatBtn() {
        FloatingActionButton fbView = new FloatingActionButton(this);
        fbView.setButtonSize(FloatingActionButton.SIZE_MINI);
        fbView.setLabelText("查看我的报价情况");
        fbView.setImageDrawable(new IconicsDrawable(this, FontAwesome.Icon.faw_user).color(Color.WHITE).actionBar());
        fbView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //查看我的报价
                mFabMenu.close(false);
                viewMyBidding();

            }
        });
        mFabMenu.addMenuButton(fbView);
        if(sType==0){
            mFabMenu.setVisibility(View.GONE);
        }
    }

    /**
     * 查看是否报价
     */
    private void viewMyBidding(){

        WebUtil.postBiddingSearch(WebUtil.getRpBiddingSearch(mApp.getDriverInfo().getId() + "", sPackageInfo.getId()+""), new JsonHttpResponseHandler() {

            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                Gson gson = new Gson();
                try {
                    ServerRpsInfo serverRpsInfo = gson.fromJson(response.toString(), ServerRpsInfo.class);
                    if (serverRpsInfo.getStatus().equals("ok") && serverRpsInfo.getMessage().equals("ok")) {

                        BiddingInfo biddingInfo = gson.fromJson(response.toString(), BiddingInfo.class);
                        if(biddingInfo.getData().isEmpty()){
                            //还未报价
                            new MaterialDialog.Builder(OrderDetailActivity.this)
                                    .title("查看我的报价")
                                    .content("此单我还没有上报价格")
                                    .positiveText("我已知悉")
                                    .negativeText("我要报价")
                                    .onNegative(new MaterialDialog.SingleButtonCallback() {
                                        @Override
                                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                            showAddBidding();
                                        }
                                    })
                                    .show();
                        }else{
                            BiddingInfo.DataBean dataBean =  biddingInfo.getData().get(biddingInfo.getData().size()-1);
                            //已报价
                            new MaterialDialog.Builder(OrderDetailActivity.this)
                                    .title("查看我的报价")
                                    .content("所用车："+dataBean.getUname()+"\n"+
                                            "最新报价价格："+dataBean.getPrice()+"\n")
                                    .positiveText("我已知悉")
                                    .negativeText("我要取消报价")
                                    .onNegative(new MaterialDialog.SingleButtonCallback() {
                                        @Override
                                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                            showDelSure();
                                        }
                                    })
                                    .show();
                        }
                    }
                } catch (Exception e) {
                    SingleToast.showToast(OrderDetailActivity.this, "查询我的报价出错:" + e.getLocalizedMessage(), 2000);
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                super.onFailure(statusCode, headers, throwable, errorResponse);
                SingleToast.showToast(OrderDetailActivity.this, "查询我的报价失败", 2000);
            }
        });
    }

    EditText mEtCarName;
    EditText mEtCarPrice;
    /**
     * 报价
     */
    private  void showAddBidding() {
        MaterialDialog dialog = new MaterialDialog.Builder(this)
                .title("添加报价")
                .customView(R.layout.dialog_customview, true)
                .cancelable(false)
                .positiveText(android.R.string.ok)
                .negativeText(android.R.string.cancel)
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        final String carName = mEtCarName.getEditableText().toString();
                        final String carPrice = mEtCarPrice.getEditableText().toString();
                        if(TextUtils.isEmpty(carName)||TextUtils.isEmpty(carPrice)){
                            SingleToast.showToast(OrderDetailActivity.this,"车牌和价格不能为空",200);
                            return;
                        }else{
                            dialog.dismiss();


                            //取消报价信息
                            WebUtil.postBiddingAdd(WebUtil.getRpBiddingAdd(getDriverInfo().getId()+"",sPackageInfo.getId()+"",carPrice,carName),
                                    new JsonHttpResponseHandler() {

                                @Override
                                public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                                    super.onSuccess(statusCode, headers, response);
                                    Gson gson = new Gson();
                                    try {
                                        ServerRpsInfo serverRpsInfo = gson.fromJson(response.toString(), ServerRpsInfo.class);
                                        if(serverRpsInfo.getStatus().equals("ok")&& serverRpsInfo.getMessage().equals("ok")) {
                                            NlServerRps nlRpsInfo = gson.fromJson(response.toString(), NlServerRps.class);
                                            SingleToast.showToast(OrderDetailActivity.this, "添加报价成功,你是第"+nlRpsInfo.getData()+"位报价者", 2000);
                                        }
                                    } catch (Exception e) {
                                        SingleToast.showToast(OrderDetailActivity.this, "添加报价出错:"+e.getLocalizedMessage(), 2000);
                                    }
                                }

                                @Override
                                public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                                    super.onFailure(statusCode, headers, throwable, errorResponse);
                                    SingleToast.showToast(OrderDetailActivity.this, "添加报价失败", 2000);
                                }
                            });

                        }

                    }
                })
                .build();
        mEtCarName = (EditText) dialog.getCustomView().findViewById(R.id.et_car_title);
        mEtCarPrice = (EditText) dialog.getCustomView().findViewById(R.id.et_car_price);
        dialog.show();
    }

    private void showDelSure(){
        new MaterialDialog.Builder(OrderDetailActivity.this)
                .title("取消报价")
                .content("确定取消报价么?")
                .positiveText(android.R.string.ok)
                .negativeText(android.R.string.cancel)
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        dialog.dismiss();

                        //取消报价信息
                        WebUtil.postBiddingRemove(WebUtil.getRpBiddingRemove(getDriverInfo().getId()+"",sPackageInfo.getId()+""),new JsonHttpResponseHandler() {

                            @Override
                            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                                super.onSuccess(statusCode, headers, response);
                                Gson gson = new Gson();
                                try {
                                    ServerRpsInfo serverRpsInfo = gson.fromJson(response.toString(), ServerRpsInfo.class);
                                    if(serverRpsInfo.getStatus().equals("ok")&& serverRpsInfo.getMessage().equals("ok")) {
                                        SingleToast.showToast(OrderDetailActivity.this, "取消报价成功", 2000);
                                    }
                                } catch (Exception e) {
                                    SingleToast.showToast(OrderDetailActivity.this, "取消报价出错:"+e.getLocalizedMessage(), 2000);
                                }
                            }

                            @Override
                            public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                                super.onFailure(statusCode, headers, throwable, errorResponse);
                                SingleToast.showToast(OrderDetailActivity.this, "取消报价失败", 2000);
                            }
                        });

                    }
                }).show();
    }





}
